package com.zhu.utils;

import com.alibaba.excel.EasyExcel;
import com.zhu.pojo.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class ExcelUtils {

    //Excel导出
    public <T> void export(List<T> data,Class<T> cls,HttpServletResponse response) throws IOException {
        //根据class类截取对应的文件名前缀
        String className = cls.toString();
        String fileName = className.substring(className.lastIndexOf(".")+1).toLowerCase() + ".xls";
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition","attachment;fileName="+fileName);
        response.setHeader("Access-Control-Expose-Headers","fileName");
        response.setHeader("fileName",fileName);
        EasyExcel.write(response.getOutputStream(), cls)
                .sheet("sheet1")
                .doWrite(data);
    }

    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }

    //Excel导入
    public void upload(){

    }

}
